import { SubjectComponent } from "./subject";
import Utils from "./utils";


const { executeInEditMode, ccclass, property } = cc._decorator;

/** 遮罩外观 （全屏透明 | 全屏黑色半透明+文字 | 透明+右下文字 ） */
export enum BlockerType {
    FullScreen = 0,
    FullScreenVisible,
    Corner,
};

/**
 * 顶层的遮盖，用于阻止操作。
 * @example
 *  //blocker支持3种外观
 *  Utils.type = 0; //全透明
    Utils.type = 1; //半透明黑+文字居中
    Utils.type = 2; //透明+文字居右下

    Utils.blocker.show(); //开启
    //做点事
    Utils.blocker.hide(); //关闭
 */
@ccclass
@executeInEditMode
export default class Blocker extends SubjectComponent {
    @property(cc.Sprite)
    bgFace: cc.Sprite = null;
    @property(cc.Label)
    descLb: cc.Label = null;

    private __desc = "Loading...";
    /** loading的文字 */
    get desc() {
        return this.__desc;
    }
    set desc(val) {
        if (this.__desc == val) {
            return;
        }
        this.__desc = val;

        this.descLb.string = this.__desc;
    }


    private __type: BlockerType = BlockerType.FullScreen;
    /** 遮罩外观 参考BLOCKER_TYPE */
    get type() {
        return this.__type;
    }
    set type(val) {
        if (this.__type == val) {
            return;
        }
        this.__type = val;
        this.refresh();
    }

    /**
     * blocked 计数
     * 当大于零时，显示全屏遮挡节点。
     * 小于零时，遮挡节点会被隐藏。
     * */
    private __blocked = 0;

    protected onDestroy(): void {
        Utils.blocker = null;
    }
    onLoad() {
        Utils.blocker = this;
        this.type = BlockerType.FullScreenVisible;
        this.refresh();
    }
    private __active() {
        this.node.opacity = 255;
        this.getComponent(cc.BlockInputEvents).enabled = true;
    }

    private __inactive() {
        this.node.opacity = 0;
        this.getComponent(cc.BlockInputEvents).enabled = false;
    }

    show() {
        this.__blocked++;
        this.refresh();
    }
    hide() {
        this.__blocked--;
        if (this.__blocked < 0) {
            console.warn("Blocker::hide, blocked < 0 ");
            this.__blocked = 0;
        }
        this.refresh();
    }
    refresh() {
        this.__blocked > 0 ? this.__active() : this.__inactive();
        // FULL_SCREEN,
        // FULL_SCREEN_VISIBLE,
        // CORNER,

        switch (this.__type) {
            case BlockerType.FullScreen:
                this.bgFace.node.opacity = 0;
                this.descLb.node.opacity = 0;
                break;
            case BlockerType.FullScreenVisible:
                this.bgFace.node.opacity = 180;
                this.descLb.node.opacity = 255;
                this.descLb.node.setPosition(0, 0);
                break;
            case BlockerType.Corner:
                this.bgFace.node.opacity = 0;
                this.descLb.node.opacity = 255;
                this.descLb.node.setPosition(275, -500);
                break;
        }
    }
};
